package com.pb.kanivets.bki.spring.business;

import com.pb.kanivets.bki.core.entities.Client;
import com.pb.kanivets.bki.core.exceptions.BusinessException;
import com.pb.kanivets.bki.core.services.IClientService;
import com.pb.kanivets.bki.spring.dao.ClientDao;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Component
public class SpringClientService implements IClientService {
    
    @Autowired
    private ClientDao clientDao;

    
    @Override
    public List<Client> listClients() {
        return clientDao.listClients();
    }

    @Override
    public Client getClient(int id) {
        return clientDao.getClient(id);
    }
    
    @Override
    public Client searchByInn(String inn) {
        return clientDao.getByInn(inn);
    }
    
    @Override
    public Client searchByPassp(String passp){
        return clientDao.getByPassp(passp);
    }
    
    @Override
    public List<Client> searchByFIO(String sName, String fName, String mName){
        return clientDao.getByFIO(sName, fName, fName);
    }
    

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void addClient(Client client) {
        if (clientDao.getByInn(client.getInn())!= null){
            throw new BusinessException("Пользователь с ИНН " + client.getInn() + " уже существует");
        }
        
        if (clientDao.getByPassp(client.getPassp())!= null){
            throw new BusinessException("Пользователь с паспортом " + client.getPassp()+ " уже существует");
        }
        client.setClientId(clientDao.newId());
        clientDao.addClient(client);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void updateClient(Client newInfo) {
        if (clientDao.getClient(newInfo.getClientId())== null){
            throw new BusinessException("Невозможно обновить информацию: клиента не существует");
        }
        clientDao.updateClient(newInfo);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void deleteClient(int id) {
        clientDao.deleteClient(id);
    }
    
}
